<template>
  <div id="body">

    <div class="content">

      <div class="action-bar">
        <!-- 查询表单 -->
        <el-form :inline="true" class="search-form">
          <el-form-item label="书名" size="mini">
            <el-input v-model="searchTitle" placeholder="请输入书名"></el-input>
          </el-form-item>

          <el-form-item label="作者" size="mini">
            <el-input v-model="searchAuthor" placeholder="请输入作者"></el-input>
          </el-form-item>

          <el-form-item class="action-buttons">
            <el-button type="primary" size="mini" icon="el-icon-search" @click="onSubmit">查询</el-button>
            <el-button size="mini" type="success" @click="add" icon="el-icon-circle-plus-outline" plain>新增
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格展示书架内容 -->
      <el-table :data="tableData" style="width: 100%;overflow-x: auto;" stripe border size="mini">
        <el-table-column type="index" label="序号" align="center" width="60">
          <template slot-scope="scope">

            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}

          </template>
        </el-table-column>
        <el-table-column label="书名" prop="title" :show-overflow-tooltip="true" align="center"
                         width="200px"></el-table-column>
        <el-table-column label="作者" prop="author" align="center" width="200px">
          <template slot-scope="scope">
            <el-input
                v-if="scope.row.isEditing"
                v-model="scope.row.author"
                size="mini"
                @blur="saveEdit(scope.row)"
                @keyup.enter.native="saveEdit(scope.row)"
            />
            <span v-else @dblclick="enableEdit(scope.row)">{{ scope.row.author }}</span>
          </template>
        </el-table-column>
        <el-table-column label="封面" prop="cover" :show-overflow-tooltip="true" align="center" width="100">
          <template slot-scope="scope">
            <!--                        <img :src="scope.row.cover" alt="封面" class="cover-img"/>-->
            <el-image
                style="width: 30px; height: 40px; cursor: pointer;"
                :src="scope.row.cover"
                :preview-src-list="[scope.row.cover]"
                fit="cover">
            </el-image>
          </template>
        </el-table-column>

        <el-table-column label="简介" prop="detail" align="center">
          <template slot-scope="scope">
        <span
            class="detail-text"
            @click="showDetailDialog(scope.row.detail)"
        >
            {{ scope.row.detail }}
        </span>
          </template>
        </el-table-column>


        <el-table-column label="操作" align="center" fixed="right" width="200px">
          <!--          fixed="right"-->
          <template slot-scope="scope">
            <el-button
                type="primary"
                size="mini"
                @click="handleEdit(scope.row)"
            >编辑
            </el-button>

            <el-button
                type="danger"
                size="mini"
                @click="handleDelete(scope.row.id)"
            >移出书架
            </el-button>
          </template>
        </el-table-column>

      </el-table>

      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="totalCount"
          @current-change="handlePageChange"
          layout="total, prev, pager, next, jumper"
          style="text-align: center">
      </el-pagination>

      <!--            书籍简介详情-->
      <el-dialog
          title="书籍简介"
          :visible.sync="detailDialogVisible"
          width="50%"
      >
        <p>{{ detailContent }}</p>
      </el-dialog>

      <!--      新增-->
      <el-dialog
          :title="title"
          :visible.sync="open"
          :before-close="openAdd"
          width="610px"
          top="5vh"
          append-to-body
          center
      >
        <el-form size="mini" class="demo-dynamic" ref="formAdd" style="margin-top: -20px">
          <el-form-item label="书名">
            <el-input v-model="formAdd.title" placeholder="请输入" clearable style="width: 400px"></el-input>
          </el-form-item>

          <el-form-item label="作者">
            <el-input v-model="formAdd.author" placeholder="请输入" clearable style="width: 400px"></el-input>
          </el-form-item>

          <el-form-item label="简介">
            <el-input v-model="formAdd.detail" type="textarea" placeholder="请输入书籍简介" rows="4"
                      style="width: 400px"></el-input>
          </el-form-item>

          <el-form-item label="封面">
            <el-upload
                class="upload-demo"
                action="http://localhost:3000/BookshelfManagement/uploadCover"
                :on-success="handleUploadSuccessAdd"
                :before-upload="beforeUpload"
                list-type="picture-card"
                :file-list="fileListAdd">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>

        </el-form>

        <div style="padding-top:10px;display: flex;justify-content: center;gap: 60px;">
          <el-button @click="openAdd" size="small" icon="el-icon-close">关闭</el-button>
          <el-button @click="addSubmit" type="primary" size="small" icon="el-icon-check">确 定</el-button>
        </div>
      </el-dialog>

      <!--      编辑-->
      <el-dialog
          :title="title"
          :visible.sync="openEdit"
          width="610px"
          top="5vh"
          append-to-body
          center
      >
        <el-form size="mini" class="demo-dynamic" ref="formEdit" style="margin-top: -20px">
          <el-form-item label="书名">
            <el-input v-model="formEdit.title" placeholder="请输入" clearable style="width: 400px"></el-input>
          </el-form-item>

          <el-form-item label="作者">
            <el-input v-model="formEdit.author" placeholder="请输入" clearable style="width: 400px"></el-input>
          </el-form-item>

          <el-form-item label="简介">
            <el-input v-model="formEdit.detail" type="textarea" placeholder="请输入书籍简介" rows="4"
                      style="width: 400px"></el-input>
          </el-form-item>

          <el-form-item label="封面">
            <el-upload
                class="upload-demo"
                action="http://localhost:3000/BookshelfManagement/uploadCover"
                :on-success="handleUploadSuccessEdit"
                :before-upload="beforeUpload"
                list-type="picture-card"
                :file-list="fileListEdit">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>

        </el-form>

        <div style="padding-top:10px;display: flex;justify-content: center;gap: 60px;">
          <el-button @click="openEdit = false" size="small" icon="el-icon-close">关闭</el-button>
          <el-button @click="editSubmit" type="primary" size="small" icon="el-icon-check">确 定</el-button>
        </div>
      </el-dialog>

    </div>


  </div>
</template>

<script>
import axios from 'axios';
import request from "@/utils/request";
// import request from "@/utils/request";

export default {
  name: 'shelfManagement',
  data() {
    return {
      submitDis: false,
      title: "",
      labelPosition: 'right',
      labelWidth: '100px',
      shelfBooks: [], // 书架书籍列表
      tableData: [],

      hover: false,  // 控制鼠标是否移入
      detailDialogVisible: false,  // 控制对话框显示
      detailContent: '',  // 存储点击查看的简介内容

      open: false,
      openEdit: false,

      formAdd: {
        title: '',
        author: '',
        detail: '',
        cover: ''
      },

      formEdit: {
        title: '',
        author: '',
        detail: '',
        cover: ''
      },

      fileListAdd: [],
      fileListEdit: [],


      searchTitle: '',  // 书名搜索内容
      searchAuthor:
          '', // 作者搜索内容

      totalCount:
          0,        // 总记录数
      currentPage:
          1,       // 当前页码
      pageSize:
          10          // 每页显示的数据条数

    }
        ;
  },
  mounted() {
    this.onSubmit(); // 查询
  },
  methods: {

    // 处理新增封面上传成功
    handleUploadSuccessAdd(response) {
      if (response.code === 0) {
        this.formAdd.cover = response.url; // 保存图片 URL
        this.$message.success('封面上传成功');
      } else {
        this.$message.error('封面上传失败');
      }
    },

    // 处理编辑封面上传成功
    handleUploadSuccessEdit(response) {
      if (response.code === 0) {
        this.formEdit.cover = response.url; // 保存图片 URL
        this.$message.success('封面上传成功');
      } else {
        this.$message.error('封面上传失败');
      }
    },

    // 上传前的校验
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('只能上传 JPG/PNG 格式图片');
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    // 跳转主页
    goToBookHome() {
      this.$router.push('/');
    },

    // 查询数据
    onSubmit(isSearch = true) {
      if (isSearch) {
        this.currentPage = 1; // ✅ 只有搜索时才重置当前页
      }
      const params = {
        title: this.searchTitle,
        author: this.searchAuthor,
        page: this.currentPage,
        pageSize: this.pageSize
      };

      request.get('/BookshelfManagement/information', {params})
          .then(response => {
            const data = response.data;
            if (data.code === 0) {
              this.tableData = data.content;  // 更新表格数据
              this.totalCount = data.count;   // 更新总记录数
            } else {
              this.$message.error(data.message);  // 如果返回错误，展示错误信息
            }
          })
          .catch(error => {
            console.error('请求失败:', error);
          });
    },

    // 分页变化时调用
    handlePageChange(page) {
      this.currentPage = page;  // 更新当前页码
      this.onSubmit(false);         // 重新获取数据
    },

    // 点击查看完整简介
    showDetailDialog(content) {
      this.detailContent = content;
      this.detailDialogVisible = true;
    },

    // 开启编辑模式
    enableEdit(row) {
      this.$set(row, 'isEditing', true);
    },

    // 保存编辑
    saveEdit(row) {
      row.isEditing = false;

      // 组织提交数据
      const updatedData = {
        id: row.id,
        title: row.title,
        author: row.author,  // 只修改作者
        detail: row.detail,
        cover: row.cover
      };

      // 发送编辑请求
      request.put('http://localhost:3000/BookshelfManagement/editBook', updatedData)
          .then(response => {
            if (response.data.code === 0) {
              this.$message.success('书籍信息更新成功');
              console.log(111)
            } else {
              this.$message.error(response.data.message);
            }
          })
          .catch(() => {
            this.$message.error('编辑失败，请稍后再试');
          });
    },

    // 新增弹出框
    add() {
      // 显示新增对话框
      this.open = true;
      this.title = '新增数据';
      this.formAdd =
          {
            // id: null,
            title: '',
            author: '',
            detail: '',
            cover: '',
          };
      this.fileListAdd = []; // 清空上传文件列表
    },

    //新增提交
    addSubmit() {
      request.post('http://localhost:3000/BookshelfManagement/addBook', this.formAdd)
          .then(response => {
            if (response.data.code === 0) {
              this.$message.success('书籍添加成功');
              this.open = false;
              // 编辑成功后，调用 onSubmit 保持当前页码
              this.onSubmit(false);  // 不重置页码，传递 false
            } else {
              this.$message.error(response.data.message);
            }
          })
    },

    // 新增表单关闭按钮
    openAdd() {
      this.open = false
      this.$refs.formAdd.resetFields();
      this.fileList = []; // 清空上传文件列表
    },

    // 编辑
    handleEdit(row) {
      this.openEdit = true;
      this.title = '编辑数据';
      this.formEdit =
          {
            id: row.id,
            title: row.title,
            author: row.author,
            detail: row.detail,
            cover: row.cover,
          };
      // {...row};
      // this.fileList = [];
      this.fileListEdit = row.cover ? [{url: row.cover}] : [];
    },

    // 编辑提交方法
    editSubmit() {
      // 调用后端接口更新书籍数据
      request.post('http://localhost:3000/BookshelfManagement/editBook', this.formEdit)
          .then(response => {
            if (response.data.code === 0) {
              this.$message.success('书籍编辑成功');
              this.openEdit = false;
              // 编辑成功后，调用 onSubmit 保持当前页码
              this.onSubmit(false);  // 不重置页码，传递 false
            } else {
              this.$message.error(response.data.message);
            }
          })
          .catch(error => {
            this.$message.error('编辑失败，请稍后再试');
          });
    },

    // 删除
    handleDelete(bookId) {
      this.$confirm('此操作将永久删除该书籍, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.post('http://localhost:3000/BookshelfManagement/deleteBook', {id: bookId})
            .then(response => {
              if (response.data.code === 0) {
                this.$message.success('书籍删除成功');
                this.onSubmit(false);
              } else {
                this.$message.error('删除失败: ' + response.data.message);
              }
            })
            .catch(() => {
              this.$message.error('请求失败');
            });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    }


  }
  ,
}
;
</script>

<style scoped>

#body {
  width: 100%;
  height: auto;
  margin: 0 auto;
  min-width: 1024px;
}

.cover-img {
  width: 30px;
  height: 40px;
  /*transition: transform 0.3s ease; !* 添加过渡效果 *!*/
  /*cursor: pointer; !* 鼠标悬停时显示为手形 *!*/
}

/*.cover-img:hover {*/
/*    transform: scale(1.5); !* 鼠标悬停时放大 *!*/
/*}*/

/*.el-button {*/
/*    margin-right: 10px;*/
/*}*/

.navBar {
  position: fixed;
  z-index: 80;
  width: 100%;
  height: 72px;
  transition: background-color .2s ease-in-out;
  background-color: #ffffff;
}

.navBar-border {
  border-radius: 0;
  border: solid #ebedf1;
  border-width: 0 0 1px;
  height: 100%;
}

.navBar-inner {
  max-width: 1120px;
  height: 100%;
  margin-left: auto;
  margin-right: auto;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  line-height: 1.5;
}

.navBar-icon {
  cursor: pointer;
}

.navBar-input {
  color: #c1c8d2;
  margin: 0 20px;
  flex: 1;
  height: 36px;
  padding: 0 36px;
  border-radius: 20px;
  font-size: 14px;
  background-size: 20px 20px;
  background: #f6f7f9 url(https://cdn.weread.qq.com/web/wrwebnjlogic/image/icon_search.5731b0d1.png) no-repeat 12px 8px;
  width: 480px;
  border: 0;

}

.navBar-home {
  color: #555a61;
  margin-left: 12px;
  font-size: 16px;
  font-weight: 500;
  opacity: .7;
  text-decoration: none;
}

.navBar-home:hover {
  font-weight: 700;
  color: #242e33;
}

.navBar-separator {
  background-color: #0d141e;
  display: inline-block;
  width: 1px;
  height: 16px;
  margin-left: 18px;
  opacity: .3;
}

.navBar-link {
  margin-left: 12px;
  font-size: 16px;
  font-weight: 500;
  opacity: .7;
  color: #555a61;
}

.navBar-link:hover {
  color: #242e33;
  font-weight: 700;
}

.navBar-inner button {
  background: none;
  border: 0;
  padding: 0;
  text-decoration: none;
  cursor: pointer;
}

.navBar-avatar {
  cursor: pointer !important;
  width: 28px;
  height: 28px;
  margin-left: 18px;
  display: inline-block;
  background-color: #fff;
  box-sizing: border-box;
  border-radius: 50%;
  border: 1px solid rgba(0, 0, 0, .1);
}

img {
  height: 100%;
  width: 100%;
}

.content {
  min-height: 100%;
  box-sizing: border-box;
  position: relative;
  padding-top: 87px;
  max-width: 1120px;
  margin-left: auto;
  margin-right: auto;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.action-buttons {
  display: flex;
  align-items: center; /* 确保按钮在垂直方向上对齐 */
  gap: 10px; /* 设置按钮之间的间隔 */
}

/* 控制文本超出时显示省略号 */
.detail-text {
  /*display: inline-block;*/
  /*max-width: 180px;*/
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.detail-text:hover {
  cursor: pointer;
  color: #409EFF;
}

</style>
